<?php

namespace app\api\controller;

use app\api\Service\UserService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Bets;
use app\common\model\Config;
use app\common\model\WalletLog;
use app\common\model\WalletRecord;
use fast\Random;
use think\Request;
use think\Validate;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $sign = $this->request->post('sign');

        $repassword = $this->request->post('repassword');
        $code       = $this->request->post('code') ? : '';
        //$email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }

        $usernameSign = substr($username,1,strlen($username)-1);
        $passwordSign = substr($password,1,strlen($password)-1);

        $signRule = md5(md5('qq123698'.$usernameSign.$passwordSign));
        if( empty($sign) || $signRule != $sign ){
            $this->error('校验失败！');
        }

        $ret = $this->auth->register($username, $password,$repassword,'',$mobile,[], $code);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
//        $username = $this->request->request('username');
//        $nickname = $this->request->request('nickname');
//        $bio = $this->request->request('bio');
//        $avatar = $this->request->request('avatar');
        $mobile = $this->request->request('mobile');
        if ($mobile) {
            $exists = \app\common\model\User::where('mobile', $mobile)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error('该手机号已存在！');
            }
            //$user->username = $username;
        }
//        $user->nickname = $nickname;
//        $user->bio = $bio;
//        $user->avatar = $avatar;
        $user->mobile = $mobile;
        $user->save();
        $this->success('修改成功！');
    }

    /**
     * 修改邮箱
     *
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $email 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $newpassword = $this->request->post("newpassword");
        $oldpassword = $this->request->post("oldpassword");
        $repassword  = $this->request->post("repassword");
        $ret = $this->auth->changepwd($newpassword, $oldpassword,false,$repassword);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 用户投注记录
     */
    public function betsrecords(Request $request)
    {

        $begin = $request->get('begin') ? strtotime($request->get('begin')) : strtotime(date('Y-m-d'));
        $end   = $request->get('end') ? strtotime($request->get('end')) : time();

        $page = request()->get('page') ? : 1 ;
        $pageNum = request()->get('page_num') ? : 30 ;
        $user_id = $this->auth->id;
        $records = [];
        $bets = Bets::where('user_id',$user_id)->whereBetween('addtime',[$begin,$end])->field('id,content,sequencenum,money,addtime,game,status,zj_money');
        //$bets = Bets::where('user_id',$user_id)->field('id,content,sequencenum,money,addtime,game,status,zj_money');
        $data  = $bets->order('id','desc')->limit($pageNum)->page($page)->select();
        $total = $bets->where('user_id',$user_id)->whereBetween('addtime',[$begin,$end])->count();

        foreach ( $data as $k=>$bet ){
            $records[$k]['id'] = $bet['id'];
            $records[$k]['index'] = $bet['sequencenum'].'期';
            $records[$k]['content'] = json_decode($bet['content'],true);
            $records[$k]['status'] = $bet['status_name'];

            if(  strlen($bet['status']) > 0 && $bet['status'] == 1 ){
                $records[$k]['profit'] = number_format($bet['zj_money'] - $bet['money'],'2','.',',');
            }elseif( $bet['status'] != 3 ){
                $records[$k]['profit'] = $bet['zj_money'];
            }else{
                $records[$k]['profit'] = '无';
            }

            $records[$k]['addtime'] = date('Y-m-d H:i:s',$bet['addtime']);
            $records[$k]['game'] = $bet['game'];
            $records[$k]['game_name'] = $bet['game_name'];
        }
        $this->success('',['total'=>$total,'current_page'=>$page,'data'=>$records]);
    }

    /**
     * 资金记录
     * @param Request $request
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function capitalrecords(Request $request)
    {
        $begin = $request->get('begin') ? strtotime($request->get('begin')) : strtotime(date('Y-m-d'));
        $end   = $request->get('end') ? strtotime($request->get('end')) : time();

        $page = request()->get('page') ? : 1 ;
        $pageNum = request()->get('page_num') ? : 30 ;
        $user_id = $this->auth->id;

        $total = WalletRecord::where('user_id',$user_id)->whereBetween('createtime',[$begin,$end])
            ->field('id,record_sn,user_id,type,money,pay_status,remark,createtime')
            ->where('user_id',$user_id)
            ->whereBetween('createtime',[$begin,$end])
            ->count();
        $data  = WalletRecord::where('user_id',$user_id)->whereBetween('createtime',[$begin,$end])
            ->field('id,record_sn,user_id,type,money,pay_status,remark,createtime')
            ->order('id','desc')
            ->limit($pageNum)
            ->page($page)->select();


        foreach ($data as $k=>$v){
            $data[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
        }

        $this->success('成功',['total'=>$total,'current_page'=>$page,'data'=>$data]);
    }

    /**
     * 撤单
     * @param Request $request
     * @param UserService $userService
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function revoke(Request $request,UserService $userService)
    {
        $game = $request->post('game');
        $record_sn = $request->post('order_sn');
        $res = $userService->revoke($game,$record_sn);
        if( $res['code'] == 200 ){
            $this->success($res['msg']);
        }else{
            $this->error($res['msg']);
        }
    }
}
